﻿/****************************** Module Header ******************************\
 * Module Name:  DataModule.cs
 * Module Version:  1.0.0 (2013-6-6)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is used to list the database products.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace UCL.Data
{
    /// <summary>
    /// 数据模型类
    /// <remarks>2013-6-6 sutroon</remarks>
    /// </summary>
    public class DataModule
    {
        public Dictionary<string, string> Params { get; set; }
        public List<string> MessageSet { get; set; }
        public string TableName { get; set; }
        public IDatabaseHelper DBH { get; set; }

        /// <summary>
        /// 构造方法
        /// </summary>
        public DataModule()
        {
            this.Params = new Dictionary<string, string>();
            MessageSet = new List<string>();
        }

        /// <summary>
        /// 需要两个参数的构造方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="idh"></param>
        public DataModule(string tableName, IDatabaseHelper idh)
            : this()
        {
            this.TableName = tableName;
            this.DBH = idh;
            this.DBH.TableName = tableName;
        }

        /// <summary>
        /// 获取指定名称的参数值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetParam(string name)
        {
            if (!this.Params.ContainsKey(name)) return string.Empty;
            Type t = this.Params[name].GetType();
            if (t == typeof(string))
            {
                return this.Params[name].ToString().Trim('\'');
            }
            return this.Params[name];
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="errmsg"></param>
        /// <param name="type">数据类型：STRING | INT | DATETIME</param>
        public void AddParam(string name, object value, string errmsg = "", string type = "STRING")
        {
            if (value == null)
            {
                if (errmsg.Length > 0) MessageSet.Add(errmsg);
                return;
            }
            string v = value.ToString();
            bool isStr = false;
            switch (type.ToLower())
            {
                case "int":
                    int iV;
                    if (!Int32.TryParse(v, out iV))
                    {
                        if (errmsg.Length > 0) MessageSet.Add(errmsg);
                        return;
                    }
                    break;
                case "datetime":
                    DateTime dtV;
                    if (!DateTime.TryParse(v, out dtV))
                    {
                        if (errmsg.Length > 0) MessageSet.Add(errmsg);
                        return;
                    }
                    isStr = true;
                    break;
                default:
                    if (string.IsNullOrEmpty(v) || v.IndexOf("'") > -1)
                    {
                        if (errmsg.Length > 0) MessageSet.Add(errmsg);
                        return;
                    }
                    isStr = true;
                    break;
            }
            this.Params[name] = isStr ? string.Format("'{0}'", v) : v;
        }

        /// <summary>
        /// 获取用于更新记录的字段语句
        /// </summary>
        /// <returns></returns>
        public string GetUpdateFieldsSql()
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in Params.Keys)
            {
                sb.AppendFormat("{0}={1},", k, Params[k]);
            }
            return sb.ToString().Trim(',');
        }

        /// <summary>
        /// 添加模型数据到数据库
        /// </summary>
        /// <returns></returns>
        public bool Insert()
        {
            if (!this.CheckProperties()) return false;
            if (MessageSet.Count > 0 || Params.Count == 0) return false;
            DBH.ExecuteNonQuery(string.Format("insert into {0} ({1}) values ({2})", this.TableName, Params.Keys.ToString(","), Params.Values.ToString(",")));
            return true;
        }

        /// <summary>
        /// 更新模型数据到数据库
        /// </summary>
        /// <param name="search"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public bool Update(string search, params object[] args)
        {
            if (!this.CheckProperties()) return false;
            if (MessageSet.Count > 0 || search.Length == 0 || this.Params.Count == 0) return false;
            DBH.ExecuteNonQuery(string.Format("update {0} set {1} where {2}", this.TableName, GetUpdateFieldsSql(), string.Format(search, args)));
            return true;
        }

        /// <summary>
        /// 获取错误信息
        /// </summary>
        /// <param name="splitor"></param>
        /// <returns></returns>
        public string GetError(string splitor = null)
        {
            if (MessageSet.Count == 0) return string.Empty;
            if (splitor == null) splitor = Environment.NewLine;
            return MessageSet.ToString(splitor);
        }

        /// <summary>
        /// 检测变量是否正确
        /// </summary>
        /// <returns></returns>
        private bool CheckProperties()
        {
            bool result = true;
            if (DBH == null)
            {
                result = false;
                MessageSet.Add("数据库连接未设置");
            }
            if (string.IsNullOrEmpty(TableName))
            {
                result = false;
                MessageSet.Add("数据表名称未设置");
            }
            return result;
        }

        /// <summary>
        /// 添加消息
        /// </summary>
        /// <param name="msg"></param>
        /// <remarks>2013-12-2 by sutroon</remarks>
        public void AddMessage(string msg)
        {
            if (this.MessageSet == null)
            {
                this.MessageSet = new List<string>();
                this.MessageSet.Add(msg);
                return;
            }
            if (!this.MessageSet.Contains(msg)) this.MessageSet.Add(msg);
        }

        /// <summary>
        /// 检测是否有消息
        /// </summary>
        /// <returns></returns>
        /// <remarks>2013-12-2 by sutroon</remarks>
        public bool HasMessage()
        {
            return this.MessageSet.Count > 0;
        }

        public void Clear()
        {
            this.Params.Clear();
            this.MessageSet.Clear();
        }
    }
}
